<!--
 * @Date: 2022-06-13 14:29:31
 * @LastEditTime: 2022-12-22 11:43:29
 * @Description: 登录
-->
<template>
  <view class="page-wrap">
    <uni-nav-bar
      title="登录"
      color="#333"
      leftIcon="left"
      backgroundColor="#fff"
      :border="false"
      :statusBar="true"
      :fixed="true"
      @clickLeft="$common.back()"
    ></uni-nav-bar>

    <template>
      <view class="loginbox">
        <!-- 				<u-navbar :border-bottom="false" title=" " :immersive="true"
					:background="{backgroundColor: 'rgba(0, 0, 0, 0)'}">
					<!-- <view style="padding-right: 20rpx;" slot="right">
				帮助
			</view> 
				</u-navbar> -->
        <!-- <view class="top">
					<view class="text">
						<view class="sys-title">{{sysConfig.site_title}}</view>
						<view class="text-content">欢迎登录~快来领取您的专属好礼吧</view>
					</view> 
				</view> -->
        <view class="imgage_bg">
          <view class="app_logo">
            <image src="/static/manghe/login/logo-text.png"></image>
          </view>
          <view class="biaodan">
            <!-- #ifdef MP-WEIXIN -->
            <!-- <button @click="login()" class="btn">微信授权登录</button> -->
            <!-- #endif -->
            <u-form :model="form" ref="uForm">
              <u-form-item prop="login" label-position="top">
                <u-input
                  color="#fff"
                  v-model="form.mobile"
                  placeholder="请输入手机号"
                  :clearable="true"
                />
              </u-form-item>
              <u-form-item prop="code" label-position="top">
                <u-input
                  style="color: #fff"
                  placeholder="请输入密码"
                  v-model="form.password"
                  type="password"
                  :clearable="true"
                ></u-input>

                <!-- <u-button :disabled="disabledCode" slot="right" :plain='true'
                  style="background-color: rgba(0,0,0,.1);border:0;color:#8062ff" :hair-line="false" size="mini"
                  @click="getCode">{{codeSecond ? `${codeSecond}秒后重新获取` : codename }}</u-button> -->
              </u-form-item>
              <u-form-item prop="code" label-position="top" v-if="!isLogin">
                <u-input
                  style="color: #fff"
                  placeholder="请输入验证码"
                  v-model="form.code"
                  type="password"
                  :clearable="true"
                ></u-input>

                <u-button
                  :disabled="disabledCode"
                  slot="right"
                  :plain="true"
                  style="
                    background-color: rgba(0, 0, 0, 0.1);
                    border: 0;
                    color: #8062ff;
                  "
                  :hair-line="false"
                  size="mini"
                  @click="getCode"
                >
                  {{ codeSecond ? `${codeSecond}秒后重新获取` : codename }}
                </u-button>
              </u-form-item>

              <u-form-item prop="code" label-position="top" v-if="tokens">
                <u-input
                  style="color: #fff"
                  placeholder="请输入验证码"
                  v-model="form.code"
                  type="number"
                  :clearable="true"
                ></u-input>

                <u-button
                  :disabled="disabledCode"
                  slot="right"
                  :plain="true"
                  style="
                    background-color: rgba(0, 0, 0, 0.1);
                    border: 0;
                    color: #8062ff;
                  "
                  :hair-line="false"
                  size="mini"
                  @click="getCode"
                >
                  {{ codeSecond ? `${codeSecond}秒后重新获取` : codename }}
                </u-button>
              </u-form-item>

              <!--      <u-form-item
                prop="invite_code"
                label-position="top"
                v-if="!isLogin"
              >
                <u-input
                  color="#fff"
                  v-model="form.invite_code"
                  placeholder="请输入邀请码"
                />
              </u-form-item> -->
            </u-form>
            <block v-if="tokens">
              <view class="login-reg">去登录</view>
            </block>
            <block v-else>
              <view class="login-reg" @click="funIsLogin">
                去{{ !isLogin ? "登录" : "注册" }}
              </view>
            </block>
            <!--    <view class="login-reg" @click="funIsLogin"
              >去{{ !isLogin ? "登录" : "注册" }}</view
            >
		 -->
            <view style="height: 15px"></view>
            <u-button
              :hair-line="false"
              @click="onPhoneLogin"
              shape="circle"
              hover-class="none"
              class="custom-style"
              :custom-style="customStyle"
            >
              {{ isLogin ? "登录" : "注册" }}
            </u-button>
          </view>

          <view class="agree-box">
            <u-checkbox
              @change="checkboxChange"
              v-model="agreeChecked"
              shape="circle"
            ></u-checkbox>
            <view class="agree-box-text">
              注册或登录即表示已阅读并同意
              <text class="book-style" @click="$common.toRule(1)">
                《用户协议》
              </text>
              和
              <text class="book-style" @click="$common.toRule(7)">
                《隐私协议》
              </text>
            </view>
          </view>
          <view class="phonesanniu" v-if="anShow">
            <view class="topshanguin">
              <view class="imgs"><text>首次注册设置用户头像、昵称</text></view>
            </view>
            <view class="containar">
              <view class="avatarUrl">
                <text>设置头像</text>
                <button open-type="chooseAvatar" @chooseavatar="onChooseAvatar">
                  <image
                    class="refreshIcon"
                    :src="headImg"
                    alt="点击上传头像"
                  ></image>
                </button>
              </view>
              <view class="nickname">
                <text>设置昵称</text>
                <input
                  class="weui-input"
                  type="nickname"
                  v-model="nickName"
                  placeholder="请输入昵称"
                  @blur="bindblur"
                />
              </view>
              <view class="btn1">
                <view class="btn-sub" @click="reg()">设置用户信息</view>
              </view>
            </view>
          </view>
        </view>
      </view>
    </template>
  </view>
</template>

<script>
import { mapGetters } from "vuex";
export default {
  data() {
    return {
      customStyle: {
        background: "#1d1d62",
        color: "#fff",
        "border-color": "#1d1d62",
      },
      headImg: "https://ypay.hui-xiang.cn/uploads/other/avatar3.png",
      nickName: "默认微信用户",
      agreeChecked: false,
      anShow: false,
      optionsData: "",
      formData: {
        loginCode: "",
        mobileCode: "",
      },
      form: {
        mobile: "13835187611",
        password: "123456",
        code: "",
      },
      showReg: false,
      sysConfig: "",
      code: "",
      codeSecond: 0,
      codename: "获取验证码",
      disabledCode: false,
      timer: null,
      isLogin: true,
      tokens: "",
    };
  },
  computed: {
    ...mapGetters(["appConfig"]),
  },
  onLoad(options) {
    console.log("options", options);
    this.optionsData = options;

    // this.login()
    this.$store.dispatch("getAppConfig").then((res) => {
      this.sysConfig = res.data;
    });
  },
  onShow() {
    this.tokens = uni.getStorageSync("token");
  },
  methods: {
    funIsLogin() {
      this.isLogin = !this.isLogin;
    },
    getCode() {
      if (this.form.mobile) {
        this.codeSecond = 60;
        this.disabledCode = true;
        this.timer = setInterval(() => {
          if (this.codeSecond >= 1) {
            this.codeSecond--;
          } else {
            this.disabledCode = false;
            clearInterval(this.timer);
            this.timer = null;
          }
        }, 1000);
        let token = uni.getStorageSync("token");
        let type = 0;
        if (token) {
          type = 2;
        } else {
          type = 1;
        }
        this.req({
          url: "/v1/sms/send",
          method: "POST",
          data: {
            mobile: this.form.mobile,
            type: type,
          },
          Loading: true,
          success: (res) => {
            console.log(res);
            // this.form.code = res.data.code
            this.$u.toast(res.msg);
            // if (res.code == 200) {
            //   uni.setStorageSync(
            //     'token',
            //     `${res.data.token_type}${res.data.access_token}`
            //   )
            //   uni.reLaunch({
            //     url: '/pages/index/index'
            //   })
            // } else {
            //   uni.showToast({
            //     title: res.msg,
            //     mask: true
            //   })
            // }
          },
        });
      } else {
        this.$u.toast("请先输入手机号");
      }
    },
    onPhoneLogin() {
      if (!this.agreeChecked) {
        uni.showToast({
          title: "请先同意协议",
          icon: "error",
          mask: true,
        });
        // this.anShow = true
        return;
      }
      if (this.isLogin) {
        // 登陆接口
        this.req({
          url: "/v1/user/loginUser",
          data: this.form,
          header: {
            Authorization: JSON.parse(
              JSON.stringify(uni.getStorageSync("token"))
            ),
          },
          Loading: true,
          success: (res) => {
            console.log(res);
            if (res.code == 200) {
              uni.setStorageSync(
                "token",
                `${res.data.token_type}${res.data.access_token}`
              );
              uni.reLaunch({
                url: "/pages/index/index",
              });
            } else {
              this.$u.toast(res.msg);
              // uni.showToast({
              //   title: res.msg,
              //   mask: true
              // })
            }
          },
        });
      } else {
        // 注册接口
        this.req({
          url: "/v1/user/registerUser",
          data: this.form,
          Loading: true,
          success: (res) => {
            console.log(res);
            if (res.code == 200) {
              this.isLogin = true;
              uni.showToast({
                title: "注册成功",
                mask: true,
              });
              uni.setStorageSync("token", res.data.access_token);
              uni.reLaunch({
                url: "/pages/index/index",
              });
            } else {
              uni.showToast({
                title: res.msg,
                mask: true,
              });
            }
          },
        });
      }
      return;
      setTimeout(() => {
        this.pageTo();
      }, 800);
      return;
      this.req({
        url: "/v1/user/login",
        data: {
          code: data.code,
        },
        success: (res) => {
          if (res.code == 200) {
            uni.setStorageSync(
              "token",
              `${res.data.token_type}${res.data.access_token}`
            );
            console.log(res);

            setTimeout(() => {
              uni.showToast({
                title: "登录成功",
                mask: true,
              });
            }, 100);

            setTimeout(() => {
              this.pageTo();
            }, 800);
          } else if (res.code == 1001) {
            this.code = data.code;
            console.log("未注册");
            this.anShow = true;
          }
        },
      });
    },
    formSubmit: function (e) {
      console.log(
        "form发生了submit事件，携带数据为：" + JSON.stringify(e.detail.value)
      );
      var formdata = e.detail.value;
      uni.showModal({
        content: "表单数据内容：" + JSON.stringify(formdata),
        showCancel: false,
      });
    },
    formReset: function (e) {
      console.log("清空数据");
    },
    uploadImage(tempFilePaths) {
      console.log(this.siteBaseUrl);
      let _this = this;
      uni.uploadFile({
        url: this.siteBaseUrl + "/v1/upload/image", //接口地址
        filePath: tempFilePaths,
        name: "image",
        success: (res) => {
          let data = JSON.parse(res.data);
          // console.log(data,'image');
          this.headImg = data.data;
          uni.hideLoading();
        },
        fail: (res) => {
          console.log(res);
        },
      });
    },
    onChooseAvatar(e) {
      const avatarUrl = e.detail.avatarUrl; // 此处是头像的临时路径
      console.log(e);
      // 需要后端配合，获得线上的地址
      this.uploadImage(avatarUrl);
    },
    bindblur(e) {
      this.nickName = e.detail.value; // 获取微信昵称
    },
    checkboxChange() {
      this.agreeChecked = true;
    },
    /**
     * @description: 统一处理登录后页面跳转传参
     * @param {*}
     * @return {*}
     */
    pageTo() {
      this.$store.dispatch("getUserInfo").then(() => {
        let pages = getCurrentPages();
        console.log(pages);

        console.log("this.optionsData", this.optionsData);
        let data = "";
        if (this.optionsData) {
          let query = this.optionsData;
          if (this.optionsData.page == "package/fuli/fuli-detail") {
            query.is_new = 1;
          }
          data = query;
        }
        /* 小程序码进入 */
        if (this.optionsData.scene) {
          let query = {};
          let arr = this.optionsData.scene.split("_");
          /**
           * 小程序码参数为 1_1_1 格式 参数间通过_分隔
           * 参数1为类型,之后参数为与后台约定的参数
           * 类型:
           * 1 幸运盒子 参数1为分享人id,参数2为盒子id
           * 未完待续...
           */
          if (arr[0] == 1) {
            query.userId = arr[1];
            query.id = arr[2];
          }
          data = query;
        }

        uni.redirectTo({
          url: `${this.optionsData.page}${this.$common.qs(this.optionsData)}`,
          fail: (err) => {
            console.log("跳转失败--", this.optionsData.page);
            uni.switchTab({
              url: `${this.optionsData.page}`,
            });
          },
        });
      });
    },

    /**
     * @description: 清除注册信息
     * @param {*}
     * @return {*}
     */
    clearForm() {
      this.formData = this.$options.data().formData;
      console.log("clearOk");
    },

    /**
     * @description: 用户注册
     * @param {*}
     * @return {*}
     */
    async reg(e) {
      let wxData = await this.$common.wxMpLogin();
      let data = {};

      data.loginCode = wxData.code;
      data.nickName = this.nickName;
      data.avatarUrl = this.headImg;
      data.invite_code = uni.getStorageSync("invite_code", "");
      /* 小程序码进入 */
      this.req({
        url: "/v1/user/register",
        data,
        success: (res) => {
          console.log(res);
          if (res.code == 200) {
            uni.setStorageSync(
              "token",
              `${res.data.token_type}${res.data.access_token}`
            );

            setTimeout(() => {
              uni.showToast({
                title: "登录成功",
                icon: "success",
                mask: true,
              });
            }, 100);

            setTimeout(() => {
              this.pageTo();
            }, 800);
          }
        },
      });
    },

    /**
     * @description: 获取注册信息
     * @param {*}
     * @return {*}
     */
    getInfo(e) {
      /* 获取登录code */
      if (this.formData.loginCode === "") {
        this.$common.wxMpLogin().then((res) => {
          this.formData.loginCode = res.code;
          this.reg("login");
        });
      }

      /* 获取手机号code */
      if (this.formData.mobileCode === "") {
        console.log(e);
        if (e.type == "getphonenumber") {
          this.formData.mobileCode = e.detail.code;
          this.reg("phone");
        }
      }
    },

    /**
     * @description:
     * @param {*}
     * @return {*}
     */
    async login() {
      if (!this.agreeChecked) {
        uni.showToast({
          title: "请先同意协议",
          icon: "error",
          mask: true,
        });
        return;
      }
      let data = await this.$common.wxMpLogin();
      console.log(data);
      this.req({
        url: "/v1/user/login",
        data: {
          code: data.code,
        },
        success: (res) => {
          if (res.code == 200) {
            uni.setStorageSync(
              "token",
              `${res.data.token_type}${res.data.access_token}`
            );
            console.log(res);

            setTimeout(() => {
              uni.showToast({
                title: "登录成功",
                icon: "success",
                mask: true,
              });
            }, 100);

            setTimeout(() => {
              this.pageTo();
            }, 800);
          } else if (res.code == 1001) {
            this.code = data.code;
            console.log("未注册");
            this.anShow = true;
            // uni.showToast({
            //   title: '请点击授权登录',
            //   icon: 'none'
            // })
          }
        },
      });
    },
  },
};
</script>

<style lang="scss">
.login-reg {
  color: #999;
  margin-top: 15rpx;
  font-size: 28rpx;
  text-align: right;
}

.loginbox {
  background: rgba(0, 0, 0, 1);
  padding-top: 100px;
}

.imgage_bg {
  align-items: center;
  min-height: 500px;
  background-image: url("/static/manghe/login/bg.png");
  background-size: cover;
  position: relative;
}

.top {
  position: relative;
}

.app_logo {
  width: 223px;
  height: 73px;
  border-radius: 16px;
  // position: absolute;
  margin-left: 40px;
  margin-top: 79px;
}

.top .text .sys-title {
  // position: absolute;
  margin-left: 10%;
  margin-top: 30rpx;
  font-size: 50rpx;
  font-weight: bold;
  color: #fff;
}

.top .text .text-content {
  // position: absolute;
  margin-left: 10%;
  margin-top: 30rpx;
  font-size: 30rpx;
  font-weight: bolder;
  color: #fff;
}

.biaodan {
  // padding: 670rpx 60rpx;
  box-sizing: border-box;
  // position: absolute;
  width: 600rpx;
  height: 50rpx;
  margin-left: 100rpx;
  top: 45%;
  color: #fff;
}

.huoqu {
  color: #00dad9;
}

.row {
  margin-bottom: 30rpx;
}

.btn {
  background-color: #50a1ea;
  color: #fff;
  font-size: 32rpx;
  margin-top: 40rpx;
}

.loginbox {
  position: relative;
  min-height: 89.2vh;
}

.other {
  position: absolute;
  width: 750rpx;
  left: 0;
  bottom: 100rpx;
  text-align: center;
}

.other image {
  width: 80rpx;
  height: 80rpx;
  margin-top: 30rpx;
}

.agree-box {
  position: absolute;
  top: 90%;
  width: 80vw;
  // margin-top: 100rpx;
  box-sizing: border-box;
  margin-left: 15vw;
  display: flex;
}

.agree-box-text {
  color: #999999;
  font-size: 24rpx;
  line-height: 36rpx;
}

.book-style {
  color: #fff;
  font-size: 24rpx;
  line-height: 36rpx;
}

.phonesanniu {
  width: 640rpx;
  height: 700rpx;
  border-radius: 20rpx;
  border: 1rpx solid #000;
  background-color: #ccc;
  background-size: 100% 100%;
  top: 100rpx;
  left: 60rpx;
  position: relative;

  .topshanguin {
    width: 100%;
    height: 25%;
    display: flex;
    align-items: center;
    justify-content: center;

    .imgs {
      font-size: 40rpx;
      font-weight: bold;
      color: #333333;
    }
  }

  .containar {
    width: 100%;
    height: 75%;

    .avatarUrl {
      padding: 30rpx 0 40rpx;
      background: #fff;

      button {
        background: #fff;
        line-height: 80rpx;
        height: auto;
        width: auto;
        padding: 20rpx 30rpx;
        border: 1rpx solid #f1f1f1;
        margin: 0;
        display: flex;
        justify-content: center;
        align-items: center;

        .avatar {
          height: 100rpx;
          width: 100rpx;
        }

        .refreshIcon {
          width: 160rpx;
          height: 160rpx;
          border-radius: 50%;
        }

        .jt {
          width: 14rpx;
          height: 28rpx;
        }
      }
    }

    .nickname {
      background: #fff;
      padding: 20rpx;
      display: flex;
      align-items: center;
      justify-content: center;
      margin: auto;
      border: 1rpx solid #f1f1f1;

      .weui-input {
        margin: auto;
        padding-left: -10rpx;
      }
    }

    .btn1 {
      width: 100%;
      margin-top: 10rpx;

      .btn-sub {
        width: 468rpx;
        margin: auto;
        height: 100rpx;
        border-radius: 25rpx;
        font-size: 40rpx;
        color: #ffffff;
        line-height: 100rpx;
        text-align: center;
        font-size: 36rpx;
        background-color: #01d9d8;
      }

      .btn-tg {
        padding-top: 15rpx;
        width: 468rpx;
        margin: auto;
        text-align: center;
      }
    }
  }
}

::v-deep .uni-input-input {
  color: #fff;
}

.custom-style {
  background: #1d1d62;
  color: #fff;
  border-color: #1d1d62;
}
</style>
